package cn.wm.client;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.wm.constant.MessageType;
import cn.wm.constant.ResultType;
import cn.wm.struct.Message;
import cn.wm.struct.MessageHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * LoginAuthReqHandler
 *
 * @author wm
 * @version 1.0
 * 2021/6/25 14:08
 **/
public class LoginAuthReqHandler extends SimpleChannelInboundHandler<Message> {
    private final static Log log = StaticLog.get();
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channel激活，请求登录程序...");
        ctx.writeAndFlush(buildLoginReq());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
        // 如果是握手应答消息，需要判断是否认证成功
        if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
            byte[] loginResult = message.getBody();
            if (loginResult[0] != ResultType.SUCCESS.value()) {
                // 握手失败，关闭连接
                ctx.close();
            } else {
                System.out.println("Login is ok : " + message);
                ctx.fireChannelRead(message);
            }
        } else
            ctx.fireChannelRead(message);
    }

    private Message buildLoginReq() {
        Message message = new Message();
        MessageHeader header = new MessageHeader();
        header.setType(MessageType.LOGIN_REQ.value());
        message.setHeader(header);
        return message;
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}
